
import { getQiNiuUpToken } from '@/api/common.js'
/**
 * 七牛云上传图片公共方法
 * @param {array} filePaths - 图片本地路径数组
 * @param {object} successCallback - 上传成功回调
 * @param {object} successCallback - 上传失败回调
 */
export function qiNiuFileUpload(filePaths, successCallback, errorCallback) {
	getQiNiuUpToken().then(res => {
		let uploadFlagArr = [];
		let qiNiuFileKeyArr = [];
		filePaths.map((item, index)=>{
			uploadFlagArr.push('start');
			// 上传调用
			uni.uploadFile({
				url: 'http://up-z1.qiniup.com/',
				filePath: item.path,
				name: 'file',
				formData: {
					token: res.data,
					key: item.key,
				},
				success: function(data) {
					if (data.statusCode == 200 && data.errMsg == "uploadFile:ok") {
						uploadFlagArr[index] = 'success';
						qiNiuFileKeyArr.push(JSON.parse(data.data).key);
					} else {
						uploadFlagArr[index] = 'error';
					}
				},
				fail: res => {
					uploadFlagArr[index] = 'error';
				}
			})
		});
		const interval = setInterval(()=>{
			if(uploadFlagArr.filter(t=>t==='success').length == uploadFlagArr.length) {
				clearInterval(interval);
				successCallback(qiNiuFileKeyArr.join(','));
			}
			if(uploadFlagArr.findIndex(t=>t==='error')>=0) {
				let errorIndex = [];
				uploadFlagArr.map((item, index)=>{
					if(item==='error') {
						errorIndex.push(index);
					}
				});
				clearInterval(interval);
				errorCallback({code: 'uploadFail', errorIndex});
			}
		}, 1000);
	}).catch(()=>{
		uni.showToast({
			title: '获取令牌异常！',
			icon: 'none',
			duration: 2000
		});
		errorCallback({code: 'qiNiuUpTokenError'});
	})
}